import csv
import datetime
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Template,  Context
from django.http import Http404, HttpResponse, HttpResponseRedirect
from nokia.tt.models import *
from django.contrib.contenttypes.models import *
from nokia.reporting.models import *
from nokia.reporting.helpers import *
from django import newforms as forms
from django.utils import simplejson


FLD_TYPES = {
    'number': [
        'SmallIntegerField',
        'FloatField',
        'IntegerField',
        'PositiveSmallIntegerField',
        'DecimalField',
        'PositiveIntegerField'
        ],
    'time': [
        'DateField',
        'DateTimeField',
        'TimeField'
        ],
    'text': [
        'CharField',
        'EmailField',
        'SlugField',
        'PhoneNumberField',
        'OrderingField',
        'TextField',
        'IPAddressField',
        'XMLField',
        'URLField',
        ],
    'bool': [
        'BooleanField'
        ],
    'related': [
        'ForeignKey',
        'ManyToManyField'
        ]
}

LOOKUP_TYPES = {
    'number': [
        'isnull',
        'gt',
        'gte',
        'lt',
        'lte',
        'range',
        ],
    'time': [
        'gt',
        'gte',
        'lt',
        'lte',
        'range',
        'isnull',
        'year',
        'month',
        'day',
        ],
    'text': [
        'contains',
        'startswith',
        'endswith',
        'regex',
        'in',
        'isnull',
        ],
    'bool': [
        ],
    'related': [
        ]
}  
QUERY_TERMS = {
    'contains': 'Contains',
    'day': 'Day',
    'endswith': 'Ends With',
    'exact': 'Exactly',
    'gt': 'Greater Than',
    'gte': 'Greater Than or Equal to',
    'in': 'In List',
    'isnull': 'Null',
    'lt': 'Less Than',
    'lte': 'Less Than or Equal to',
    'month': 'Month',
    'range': 'Between',
    'regex': 'Regular Expression',
    'startswith': 'Begins With',
    'year': 'Year'
}

def get_field_type(fld_type):
    """Search through FLD_TYPES and return the key for the type of field"""
    for k,v in FLD_TYPES.items():
        if fld_type in v:
            return k

def get_poss_lookup_types(fld_type):
    return LOOKUP_TYPES.get(get_field_type(fld_type),None)

def fields_for_model(request):
    """Get the model from GET and return html for options"""
    template = Template("""{% for o in options %}<option {% if o.selected %}
    selected="selected"{% endif %} value="{{ o.value }}">{{ o.text }}</option>{% endfor %}""")
    output = request.GET.get('format','html')
    id = request.GET.get('id', None)
    if id:
        report = Report.objects.get(pk=id)
        field_ids = [f.id for f in report.fields.all()]
        opts = possible_fields(report.type.model)
        options = []
        for o in opts:
            dikt = {'value':o[0], 'text':o[1]}
            if o[0] in field_ids:
                dikt['selected'] = True
            options.append(dikt)
    else:
        ct_id = request.GET['model']
	model = ContentType.objects.get(pk=ct_id).model
        fields = possible_fields(model)
        options = [{'value':f[0], 'text':f[1]} for f in fields]
	print options
    if output == 'json': #not sure if I'm gonna need this
	    return HttpResponse(simplejson.dumps(options))
    return HttpResponse(template.render(Context({'options': options})))

def get_field_and_type(class_reg,fld_name):
	try:
		fld = class_reg.dj_model._meta.get_field(fld_name)
	except:
		pass


def filter_fields(request,id):
	"""Given the report id, return a list of fields to put in a select"""
	reporter = Report.objects.get(pk=id).get_report()
	class_reg = getattr(reporter.register,reporter.model.__name__)
	field_choices = [(f.name, prettify_string(f.name)) \
						for f in class_reg._fields + class_reg._m2ms]
	f = forms.Form()
	f.fields['fields'] = forms.ChoiceField(choices=field_choices,
							help_text="Choose a field to filter on")
	return HttpResponse(f.as_p())


